package com.sto.stoapp.activity.aviation.jipaoqi;

import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.manager.BlueWeigthManager;
import com.sto.stoapp.thread.BaseThread;

public class BearingBlueThread extends BaseThread {

	public static final int BLUETOOTH_NO_SETUP = 0x11;
	public static final int CONNECT_START = 0x22;
	public static final int BLUETOOTH_CONNECTION_ERROR = 0x23;
	public static final int CONNECT_OBJ = 0x33;

	final private BlueWeigthManager blueManager;
	private Handler handler;
	Context mContext;

	public BearingBlueThread(Context mContext, Handler handler) {
		super(mContext);
		this.mContext = mContext;
		this.handler = handler;
		blueManager = new BlueWeigthManager(mContext, handler,
				StoFilePreference.getInstance(mContext)
						.getBluetoothMacAddress());
	}

	@Override
	public void run() {
		super.run();
		if (blueManager.bluetoothIsEnabled()
				&& blueManager.isBonded(StoFilePreference.getInstance(mContext)
						.getBluetoothMacAddress())) {

			Message msg = new Message();
			msg.what = CONNECT_START;
			handler.sendMessage(msg);
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			BluetoothSocket socket = blueManager.connectBearing();
			if (socket != null) {
				Message msg2 = new Message();
				msg2.what = CONNECT_OBJ;
				msg2.obj = socket;
				handler.sendMessage(msg2);
			} else {
				// TODO 发送消息提示Mac地址错误,或者此地址已被其他把枪连接
				Message msg3 = handler
						.obtainMessage(BLUETOOTH_CONNECTION_ERROR);
				msg3.sendToTarget();
			}

		} else {
			Message msg = new Message();
			msg.what = BLUETOOTH_NO_SETUP;
			handler.sendMessage(msg);
		}

	}

	/**
	 * 关闭连接
	 */
	public void cancel() {
		blueManager.cancelConnect();
		cancelDialog();
	}

}
